const router = require('koa-router')();
const { 
    genTimeStamp,
    mobileReg,
    emailReg,
    resBody,
    aesEncrypt,
    aesDecrypt
} = require("../../utils")
const { models, sequelize } = require('../../utils/db');

// 更新session-user-info
async function setUserInfoSession(ctx, usersId) {
    let userInfo = await models.users_model.findAll({
        raw: true,
        where: {
            users_id: usersId
        }
    });
    ctx.session.userInfo = {
        users_id: userInfo[0].users_id,
        nickname: userInfo[0].nickname,
        avatar: userInfo[0].head_pic,
        email: userInfo[0].email,
        mobile: userInfo[0].mobile,
        province: userInfo[0].province,
        city: userInfo[0].city,
        district: userInfo[0].district,
        like: userInfo[0].like,
        collect: userInfo[0].collect
    };
}
// 昵称唯一性验证
async function onlyNicknameRepeat(name, usersId) {
    let nicknameRepeat = await models.users_model.findAll({
        raw: true,
        where: {
            nickname: name
        }
    })
    if (!usersId && nicknameRepeat.length > 0) {
        throw ({
            ...resBody.paramError,
            msg: '用户昵称已存在'
        });
    }
    if (usersId && nicknameRepeat.length > 0) {
        let userGroup = nicknameRepeat.filter(item => item.users_id !== usersId);
        if (userGroup.length > 0) {
            throw ({
                ...resBody.paramError,
                msg: '用户昵称已存在'
            });
        }
    }
}

// 用户注册
router.post('/userReg', async(ctx, next) => {
    const {
        nickname = '',
        passWord = '',
        againPassWord = '',
        email = '',
        phone = null,
        verificaCode = '',
        agree = false 
    } = ctx.request.body;
    if (!nickname ||
        !passWord ||
        !againPassWord ||
        !email ||
        !verificaCode ||
        !agree) {
            throw (resBody.paramError)
        }
    await onlyNicknameRepeat(nickname);
    const sessionVerifyRegCode = ctx.session.verifyRegCode;
    if (verificaCode.toLowerCase() !== sessionVerifyRegCode) {
        throw (resBody.verifyCodeErr);
    }
    if (passWord.length < 6 || passWord.length > 18) {
        throw ({
            ...resBody.paramError,
            msg: '密码需要6-18位数字或字母'
        });
    }
    if (passWord !== againPassWord) {
        throw ({
            ...resBody.paramError,
            msg: '两次输入密码不一致'
        });
    }
    if (!emailReg.test(email)) {
        throw ({
            ...resBody.paramError,
            msg: '邮箱格式错误,请重新输入!'
        });
    }
    if (!mobileReg.test(phone) && phone) {
        throw ({
            ...resBody.paramError,
            msg: '手机号码错误,请重新输入!'
        });
    }
    let usersId = genTimeStamp();
    let avatar = `avatar${parseInt(Math.random()*(110+1),10)}.jpg`;
    let aesEncryptPwd = aesEncrypt(passWord);
    await sequelize.transaction(async t => {
        await models.users_model.create(
            {   
                users_id: usersId,
                nickname: nickname,
                password: aesEncryptPwd,
                mobile: phone,
                email: email,
                head_pic: avatar,
                creat_time: new Date
            }, {
                transaction: t,
                fields: ['users_id', 'nickname', 'password', 'mobile', 'email', 'head_pic', 'creat_time']
            }
        );
    })
    await setUserInfoSession(ctx, usersId);
    ctx.body = {
        ...resBody.success,
        msg: '注册成功！'
    };
});

// 用户登陆
router.post('/userLogin', async(ctx, next) => {
    const {
        nickname = '',
        passWord = '',
        verificaCode = '',
        agree = false 
    } = ctx.request.body;
    if (!nickname ||
        !passWord ||
        !verificaCode ||
        !agree) {
            throw (resBody.paramError)
        }
    const sessionVerifyLoginCode = ctx.session.verifyLoginCode;
    if (verificaCode.toLowerCase() !== sessionVerifyLoginCode) {
        throw (resBody.verifyCodeErr)
    }
    let nicknameRepeat = await models.users_model.findAll({
        raw: true,
        where: {
            nickname: nickname
        }
    })
    if (nicknameRepeat.length === 0) {
        throw (resBody.userNotVerified);
    }
    if (passWord !== aesDecrypt(nicknameRepeat[0].password)) {
        throw (resBody.passWordErr);
    }
    let usersId = nicknameRepeat[0].users_id;
    await setUserInfoSession(ctx, usersId);
    ctx.body = {
        ...resBody.success,
        msg: '登陆成功！'
    };
})

// 用户退出登陆
router.post('/loginOut', async(ctx, next) => {
    ctx.session = null;
    ctx.body = resBody.success;
})

// 修改用户资料
router.post('/updateInfo', async(ctx, next) => {
    const params = ctx.request.body;
    const usersId = params.users_id;
    let updateParams = {};
    for (let item in params) {
        if (params[item] && item !== 'users_id') {
            if (item === 'avatar') {
                updateParams['head_pic'] = params[item]
                continue;
            }
            updateParams[item] = params[item];
        }
    }
    if (updateParams.nickname) {
        await onlyNicknameRepeat(updateParams.nickname, usersId);
    }
    if (updateParams.email && !emailReg.test(updateParams.email)) {
        throw ({
            ...resBody.paramError,
            msg: '邮箱格式错误,请重新输入!'
        });
    }
    if (updateParams.mobile && !mobileReg.test(updateParams.mobile)) {
        throw ({
            ...resBody.paramError,
            msg: '手机号码错误,请重新输入!'
        });
    }
    try {
        await sequelize.transaction(async t => {
            await models.users_model.update(updateParams, {
                    where: {
                        users_id: params.users_id
                    },
                    transaction: t,
                }
            );
        })
        await setUserInfoSession(ctx, usersId);
        ctx.body = resBody.success;
    } catch (error) {
        throw ({
            ...resBody.failed,
            msg: error
        });
    }
})

// 获取用户信息
router.post('/userInfo', async(ctx, next) => {
    ctx.body = {
        ...resBody.success,
        data: ctx.session.userInfo || ''
    };
})

module.exports = router
